package tool;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;

/**
 * 有序读取属性文件(默认的Properties是基于hashtable的，取值是无序的)
 * @author Xuyuji
 *
 */
public class OrderedProperties extends Properties {
    private static final long serialVersionUID = -4627607243846121965L;
    private final LinkedHashSet<Object> keys = new LinkedHashSet<Object>();

    public Enumeration<Object> keys() {
        return Collections.<Object> enumeration(keys);
    }

    public Object put(Object key, Object value) {
        keys.add(key);
        return super.put(key, value);
    }
    
    public synchronized Object remove(Object key) {
        keys.remove(key);
        return super.remove(key);
    }

    public Set<Object> keySet() {
        return keys;
    }

    public Set<String> stringPropertyNames() {
        Set<String> set = new LinkedHashSet<String>();
        for (Object key : this.keys) {
            set.add((String) key);
        }
        return set;
    }
    
    public static void main(String[] args) throws Exception {
    	Properties p = new OrderedProperties();
		p.load(new InputStreamReader(new FileInputStream("./resources/file.conf"), "UTF-8"));
		
		for(Object o : p.keySet()){
			System.out.println(o);
		}
	}
}
